package ethvlans

import (
	"strconv"
	"strings"
)

// Parse 解析字符串表示的 VLAN 范围
// 格式："1-100,102,500-520"
func Parse(s string) EthVLANs {
	var vlans = New()

	for _, chunk := range strings.Split(s, ",") {
		chunk = strings.TrimSpace(chunk)

		if strings.Contains(chunk, "-") {
			subStr := strings.SplitN(chunk, "-", 2)
			st, err1 := strconv.Atoi(strings.TrimSpace(subStr[0]))
			end, err2 := strconv.Atoi(strings.TrimSpace(subStr[1]))
			if err1 != nil || err2 != nil || end < st {
				return nil
			}
			for ; st <= end; st++ {
				vlans.Add(st)
			}

		} else {
			n, err := strconv.Atoi(chunk)
			if err != nil {
				return nil
			}
			vlans.Add(n)
		}
	}
	return vlans
}

// AddFromParse 从字符串中添加 VLAN
func (v EthVLANs) AddFromParse(s string) error {
	v.Add(Parse(s).Slice()...)
	return nil
}
